package cn.s1995.sloth.bizs.converter;

import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.s1995.sloth.admin.api.entity.SysDictItem;
import cn.s1995.sloth.admin.api.feign.RemoteDictService;
import cn.s1995.sloth.bizs.annotation.SysDictType;
import cn.s1995.sloth.common.core.util.R;
import cn.s1995.sloth.common.core.util.SpringContextHolder;
import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.metadata.GlobalConfiguration;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.metadata.property.ExcelContentProperty;

import java.lang.reflect.Field;
import java.util.List;
import java.util.Optional;

/**
 * 系统字典转换器
 */
public class SysDictConverter implements Converter<Object> {

    @Override
    public WriteCellData<String> convertToExcelData(Object value, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) throws Exception {
        Field field = contentProperty.getField();
        String valueStr;
        SysDictType annotation = field.getAnnotation(SysDictType.class);
        String dictType = annotation.value();
        if (StrUtil.isBlank(dictType)) {
            return new WriteCellData<>("");
        }
        RemoteDictService sysDictService = SpringContextHolder.getBean(RemoteDictService.class);
        R<List<SysDictItem>> r = sysDictService.getDictByType(dictType);
        if (ObjectUtil.isNotEmpty(r.getData())) {
            if (value instanceof Boolean boolVal) {
                valueStr = BooleanUtil.isTrue(boolVal) ? "1" : "0";
            } else {
                valueStr = String.valueOf(value);
            }
            Optional<SysDictItem> itemOptional = r.getData().stream().filter(e -> valueStr.equals(e.getItemValue())).findAny();
            if (itemOptional.isPresent()) {
                return new WriteCellData<>(itemOptional.get().getLabel());
            }
        }
        return new WriteCellData<>("");
    }
}
